package william.tree;

/**
 * @author ZhangShenao
 * @date 2024/3/19
 * @description <a href="https://leetcode.cn/problems/count-complete-tree-nodes/description/">...</a>
 */
public class Leetcode222_完全二叉树的节点个数 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 采用递归实现
     * 二叉树的节点数量=左子树节点数+右子树节点数+1
     * <p>
     * 时间复杂度O(N) 需要遍历树一次
     * 空间复杂度O(logN) 递归栈深度=树高度
     */
    public int countNodes(TreeNode root) {
        //递归终止条件
        if (root == null) {
            return 0;
        }

        //二叉树的节点数量=左子树节点数+右子树节点数+1
        return (countNodes(root.left) + countNodes(root.right) + 1);
    }
}
